package com.owc.service.impl.admin;

import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.common.exception.NoPermissionException;
import com.owc.common.tool.BeanUtils;
import com.owc.dao.AdminUserMapper;
import com.owc.domain.BaseResult;
import com.owc.domain.dto.UserInfo;
import com.owc.domain.entity.AdminUser;
import com.owc.domain.entity.User;
import com.owc.domain.vo.admin.AdminLoginVo;
import com.owc.filter.content.SecurityContextHolder;
import com.owc.filter.content.UserDetail;
import com.owc.service.OwcService;
import com.owc.service.admin.AdminService;
import com.owc.service.app.PermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author Jackies
 * @Date 2019/12/8 21:56
 * @Description TODO://
 **/
@Service
public class AdminServiceImpl implements AdminService {

    private final OwcService owcService;

    public AdminServiceImpl(OwcService owcService) {
        this.owcService = owcService;
    }

    @Resource
    private AdminUserMapper adminUserMapper;

    @Override
    public String login(AdminLoginVo adminLoginVo) {

        ExceptionEnum baseException = ExceptionEnum.USERNAME_OR_PWD_ERR;

        Optional<AdminUser> optionalAdminUser = selectByUserName(adminLoginVo.getUserName());
        if(!optionalAdminUser.isPresent()){
            throw new BadRequestException(baseException);
        }

        if(!optionalAdminUser.get().getPassword().equals(adminLoginVo.getPassword())){
            throw new BadRequestException(baseException);
        }
        //Build JWT token.
        return PermissionService.signatureJwtToken(owcService.converterFromExample(optionalAdminUser.get())
                .map(UserDetail::new)
                .orElseThrow(() -> new BadRequestException(ExceptionEnum.UNKNOWN_ERR)));
    }

    @Override
    public Optional<AdminUser> selectByUserName(String userName) {
        return Optional.ofNullable(adminUserMapper.selectByUserName(userName));
    }

    @Override
    public UserInfo getUserInfo() {
        Optional<AdminUser> optUser = selectByUserName(SecurityContextHolder.getCurrentUserName());
        if(!optUser.isPresent()) throw new NoPermissionException(ExceptionEnum.USER_INVALID_ERR);
        return Objects.requireNonNull(BeanUtils.transformFrom(optUser.get(), UserInfo.class));
    }
}
